﻿namespace BEGDC.CC.Web.UserControls.OCR
{
    using System;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Collections;
    using BEGDC.CC.BL.CCFlow.OCR;
    using BEGDC.CC.Entity;
    using BEGDC.CC.BL.Workflow;
    using BEGDC.CC.BL.Common;
    using BEGDC.Utility.Castle;
    using BEGDC.CC.BL.Common.Query;

    /// <summary>
    ///		Summary description for DeptVPApprove.
    /// </summary>
    public class LvLeaderApproval : BaseOCR
    {
        #region Variables
        protected BEGDC.CC.Web.UserControls.OCR.OCRCtrl OCRCtrl;
        protected System.Web.UI.WebControls.Button Btn_Submit;
        protected System.Web.UI.WebControls.Button Btn_Query;
        protected System.Web.UI.WebControls.TextBox tbOperationFlag;
        protected System.Web.UI.WebControls.TextBox tbOperationContent;
        protected System.Web.UI.WebControls.TextBox tbComment;
        protected System.Web.UI.WebControls.Button Btn_Reject;
        protected System.Web.UI.HtmlControls.HtmlTableRow TR_title;
        protected System.Web.UI.WebControls.Button Btn_Reply;
        protected BEGDC.CC.Web.Common.StampCtrl StampCtrl1;
        protected System.Web.UI.WebControls.Label lbAppNo;
        protected BEGDC.CC.Web.UserControls.CV.CVPrintCtrl cvPrintCtrl;
        protected System.Web.UI.WebControls.Button btnClose;

        protected System.Web.UI.WebControls.TextBox tbIsNeedNextLvApprover;
        protected System.Web.UI.WebControls.TextBox tbLvApprover;

        #endregion

        #region Properties
        private bool IsQuery
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                return state == SysDicItem.ProjectStatusFlag.QUERY;
            }
        }

        private bool IsView
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                if (state == SysDicItem.ProjectStatusFlag.View || state == SysDicItem.ProjectStatusFlag.CANCEL
                    || state == SysDicItem.ProjectStatusFlag.Pending || state == SysDicItem.ProjectStatusFlag.End
                    || state == SysDicItem.ProjectStatusFlag.Participation)
                    return true;
                else
                    return false;
            }
        }
        protected string Step
        {
            get
            {
                IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                FlowInstance flowInstance = queryService.QueryFlowInstance(this.AppID);
                if (flowInstance == null)
                    return "Close";
                else
                    return flowInstance.CurrentActiveStep.StepCode;
            }
        }
        #endregion

        private void Page_Load(object sender, System.EventArgs e)
        {
            if (!this.IsPostBack)
            {
                base.PreInitForm();

                //this.Btn_Submit.Attributes["onclick"] = "javascript:OnSubmit();";
                this.Btn_Submit.Attributes["onclick"] = "javascript:OnSubmit(" + Request.QueryString["FlowID"] + ")";
                this.Btn_Query.Attributes.Add("onclick", "javascript:OpenQueryPane(" + Request.QueryString["AppID"] + ");");
                this.Btn_Reject.Attributes.Add("onclick", "javascript:OpenCommentPane();");
                this.Btn_Reply.Attributes.Add("onclick", "javascript:OpenReplyPane(" + Request.QueryString["FlowID"] + ");");
                this.btnClose.Attributes.Add("onclick", "javascript:SimpleCloseWindow();");

                InitForm();

                if (this.IsView)
                {
                    this.TR_title.Visible = false;
                }

                if ((!(this.Step == BEGDC.CC.BL.Workflow.WorkTransition.OCR_Lv4Approval ||
                    this.Step == BEGDC.CC.BL.Workflow.WorkTransition.OCR_Lv3Approval ||
                    this.Step == BEGDC.CC.BL.Workflow.WorkTransition.OCR_Lv2Approval ||
                    this.Step == BEGDC.CC.BL.Workflow.WorkTransition.OCR_Lv1Approval) && !this.IsQuery)
                    || Request.Url.AbsoluteUri.IndexOf("workflowview") >= 0)
                {
                    this.Btn_Reply.Visible = false;
                    this.Btn_Query.Visible = false;
                    this.Btn_Reject.Visible = false;
                    this.Btn_Submit.Visible = false;
                }

                IQuery query = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                FlowInstance flowInstance = query.QueryFlowInstance(this.AppID);
                if (flowInstance != null && flowInstance.CurrentActiveStep.StepCode != BEGDC.CC.BL.Workflow.WorkTransition.OCR_Lv1Approval)
                {
                    if (query.IsNeedNextLvApprover(flowInstance.FlowID, flowInstance.CurrentActiveStep.StepCode))
                        this.tbIsNeedNextLvApprover.Text = "Yes";
                }
            }
            ButtonStatusSetting();
        }

        #region ControlStatusSetting
        private void ControlStatusSetting(Accessibility access)
        {
            if (access == Accessibility.Readonly)
            {
                this.DisableChildrenControls(this);
                //this.stampCtrl1.Visible = false;
            }
        }
        #endregion

        #region InitForm
        private void InitForm()
        {
            bool isReadOnly = true;
            long flowId = this.LoadApplication();

            if (this.Application != null)
            {
                if (this.Application.AppNo != string.Empty)
                    this.lbAppNo.Text = "Application No:" + this.Application.AppNo;

                OCRCtrl.isCoveredPerson = !this.Application.IsTransition;
                OCRCtrl.isReadOnly = isReadOnly;
                OCRCtrl.DisableEditSSME();
            }
            else
            {
                WebUtility.Go2ErrorPage(this.Page, "wrong Application ID");
            }
        }
        #endregion

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Btn_Reply.Click += new EventHandler(this.Btn_Reply_Click);
            this.Btn_Query.Click += new EventHandler(this.Btn_Query_Click);
            this.Btn_Reject.Click += new EventHandler(this.Btn_Reject_Click);
            this.Btn_Submit.Click += new EventHandler(this.Btn_Submit_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        #region BuildObjects

        private BEGDC.CC.Entity.Application BuildApplication()
        {
            IOCR OCRService = AppContainer.Instance[ServiceConst.OCRService] as IOCR;
            BEGDC.CC.Entity.Application App = OCRService.GetApplication(this.AppID);
            return App;
        }

        #endregion

        #region Submit
        private void Btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                BEGDC.CC.Entity.Application App = BuildApplication();
                IOCR OCRService = AppContainer.Instance[ServiceConst.OCRService] as IOCR;
                BEGDC.CC.BL.UserManagement.IUser userService = AppContainer.Instance[ServiceConst.UserService] as BEGDC.CC.BL.UserManagement.IUser;

                Employee nextLvApprover = null;
                string lv3ApproverNo = "";
                string lv2ApproverNo = "";
                string lv1ApproverNo = "";

                if (!string.IsNullOrEmpty(this.tbLvApprover.Text) && this.tbLvApprover.Text.Contains("_"))
                {
                    string[] temp = this.tbLvApprover.Text.Split('_');
                    lv3ApproverNo = temp[0];
                    lv2ApproverNo = temp[1];
                    lv1ApproverNo = temp[2];
                }

                Employee currentUser = ((CCIdentity)HttpContext.Current.User.Identity).UserInfo;

                //// Complete current approve
                //if (!string.IsNullOrEmpty(this.tbLvApprover.Text) && this.Step != BEGDC.CC.BL.Workflow.WorkTransition.OCR_Lv1Approval)
                //{
                //    nextLvApprover = userService.GetUserByID(this.tbLvApprover.Text);
                //}
                //OCRService.SubmitLVLeadApproval(App, nextLvApprover, this.Step, this.tbComment.Text);

                if (string.IsNullOrEmpty(this.tbLvApprover.Text) ||
                    this.Step == BEGDC.CC.BL.Workflow.WorkTransition.OCR_Lv1Approval)
                {
                    OCRService.SubmitLVLeadApproval(App, nextLvApprover, this.Step, this.tbComment.Text);
                }
                else if (this.Step == BEGDC.CC.BL.Workflow.WorkTransition.OCR_Lv2Approval)
                {
                    if (!string.IsNullOrEmpty(lv3ApproverNo) || !string.IsNullOrEmpty(lv2ApproverNo) || string.IsNullOrEmpty(lv1ApproverNo))
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert('Lv2 approval could not be performed. 2级审批不能进行!');</script>");
                        return;
                    }

                    this.SubmitLV2LeadApproval(OCRService, userService, currentUser, App, lv1ApproverNo);
                }
                else if (this.Step == BEGDC.CC.BL.Workflow.WorkTransition.OCR_Lv3Approval)
                {
                    if (!string.IsNullOrEmpty(lv3ApproverNo) || string.IsNullOrEmpty(lv2ApproverNo))
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert('Lv3 approval could not be performed. 3级审批不能进行!');</script>");
                        return;
                    }

                    this.SubmitLV3LeadApproval(OCRService, userService, currentUser, App, lv2ApproverNo, lv1ApproverNo);
                }
                else if (this.Step == BEGDC.CC.BL.Workflow.WorkTransition.OCR_Lv4Approval)
                {
                    if (string.IsNullOrEmpty(lv3ApproverNo))
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert('Lv4 approval could not be performed. 4级审批不能进行!');</script>");
                        return;
                    }

                    this.SubmitLV4LeadApproval(OCRService, userService, currentUser, App, lv3ApproverNo, lv2ApproverNo, lv1ApproverNo);
                }
                else
                {
                    Page.RegisterClientScriptBlock("", "<script>alert('Level approval could not be performed. 级别审批不能进行!');</script>");
                    return;
                }

                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM002 + "');window.close();</script>");
            }
        }

        #region Submit LV4 Lead Approval

        private void SubmitLV4LeadApproval(IOCR OCRService, BEGDC.CC.BL.UserManagement.IUser userService, Employee currentUser, BEGDC.CC.Entity.Application App, string lv3ApproverNo, string lv2ApproverNo, string lv1ApproverNo)
        {
            if (string.IsNullOrEmpty(lv3ApproverNo)) return;

            if (lv3ApproverNo != currentUser.Id)
            {
                Employee nextLvApprover = userService.GetUserByID(lv3ApproverNo);
                OCRService.SubmitLVLeadApproval(App, nextLvApprover, WorkTransition.OCR_Lv4Approval, this.tbComment.Text);
            }
            else
            {
                OCRService.SubmitLVLeadApproval(App, currentUser, WorkTransition.OCR_Lv4Approval, this.tbComment.Text);
                if (string.IsNullOrEmpty(lv2ApproverNo))
                {
                    OCRService.SubmitLVLeadApproval(App, null, WorkTransition.OCR_Lv3Approval, this.tbComment.Text);
                }
                else
                {
                    this.SubmitLV3LeadApproval(OCRService, userService, currentUser, App, lv2ApproverNo, lv1ApproverNo);
                }
            }
        }

        #endregion

        #region Submit LV3 Lead Approval

        private void SubmitLV3LeadApproval(IOCR OCRService, BEGDC.CC.BL.UserManagement.IUser userService, Employee currentUser, BEGDC.CC.Entity.Application App, string lv2ApproverNo, string lv1ApproverNo)
        {
            if (string.IsNullOrEmpty(lv2ApproverNo)) return;

            if (lv2ApproverNo != currentUser.Id)
            {
                Employee nextLvApprover = userService.GetUserByID(lv2ApproverNo);
                OCRService.SubmitLVLeadApproval(App, nextLvApprover, WorkTransition.OCR_Lv3Approval, this.tbComment.Text);
            }
            else
            {
                OCRService.SubmitLVLeadApproval(App, currentUser, WorkTransition.OCR_Lv3Approval, this.tbComment.Text);

                if (string.IsNullOrEmpty(lv1ApproverNo))
                {
                    OCRService.SubmitLVLeadApproval(App, null, WorkTransition.OCR_Lv2Approval, this.tbComment.Text);
                }
                else
                {
                    this.SubmitLV2LeadApproval(OCRService, userService, currentUser, App, lv1ApproverNo);
                }
            }
        }

        #endregion

        #region Submit LV2 Lead Approval

        private void SubmitLV2LeadApproval(IOCR OCRService, BEGDC.CC.BL.UserManagement.IUser userService, Employee currentUser, BEGDC.CC.Entity.Application App, string lv1ApproverNo)
        {
            if (string.IsNullOrEmpty(lv1ApproverNo)) return;

            if (lv1ApproverNo != currentUser.Id)
            {
                Employee nextLvApprover = userService.GetUserByID(lv1ApproverNo);
                OCRService.SubmitLVLeadApproval(App, nextLvApprover, WorkTransition.OCR_Lv2Approval, this.tbComment.Text);
            }
            else
            {
                OCRService.SubmitLVLeadApproval(App, currentUser, WorkTransition.OCR_Lv2Approval, this.tbComment.Text);
                OCRService.SubmitLVLeadApproval(App, null, WorkTransition.OCR_Lv1Approval, this.tbComment.Text);
            }
        }

        #endregion

        #endregion

        #region Reject
        private void Btn_Reject_Click(object sender, EventArgs e)
        {
            try
            {
                IOCR OCRService = AppContainer.Instance[ServiceConst.OCRService] as IOCR;
                OCRService.RejectEVPApproval(Convert.ToInt64(Request.QueryString["FlowID"]), WorkTransition.Reject, this.tbComment.Text);

                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM002 + "');window.close();</script>");
            }
        }
        #endregion

        #region Query
        private void Btn_Query_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.tbOperationFlag.Text == "query")
                {
                    IOCR OCRService = AppContainer.Instance[ServiceConst.OCRService] as IOCR;
                    OCRService.Query(Convert.ToInt64(Request.QueryString["FlowID"]), this.tbOperationContent.Text, Session["Comment"].ToString());

                    Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
                }
            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM002 + "');window.close();</script>");
            }
        }
        #endregion

        #region Export
        private void Btn_Export_Click(object sender, EventArgs e)
        {
            try
            {
                ExcelTool.ICCExcelExport excelExport;
                if (this.Application.IsTransition)
                    excelExport = new ExcelTool.ExportCRFormA();
                else
                    excelExport = new ExcelTool.ExportCRFormB();
                excelExport.Export(this.Page, this.AppID);
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');</script>");

            }
            catch (BEGDC.Utility.ExceptionManagement.GDCException exp)
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.ErrorMessage.Export_0001 + "');</script>");
            }
        }
        #endregion

        #region ButtonStatusSetting
        protected override void ButtonStatusSetting()
        {
            if (this.Access == null)
                return;

            this.Btn_Submit.Visible = this.Access.IsButtonVisible(OCRTransitionList.Approve);
            //this.Btn_Query.Visible = this.Access.IsButtonVisible(OCRTransitionList.Query);
            this.Btn_Query.Visible = true;
            this.Btn_Reject.Visible = this.Access.IsButtonVisible(OCRTransitionList.Reject);
            this.Btn_Reply.Visible = this.Access.IsButtonVisible(OCRTransitionList.Reply);
            this.cvPrintCtrl.ProcessType = WorkflowTypes.OCR;
            this.cvPrintCtrl.Visible = this.Access.IsButtonVisible(OCRTransitionList.Copy);
        }
        #endregion

        #region Reply
        private void Btn_Reply_Click(object sender, EventArgs e)
        {
            try
            {
                IOCR OCRService = AppContainer.Instance[ServiceConst.OCRService] as IOCR;

                OCRService.ReplyQuery(Convert.ToInt64(Request.QueryString["FlowID"]), WebUtility.DeCodeString(Server, tbComment.Text));
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM002 + "');window.close();</script>");
            }
        }
        #endregion

        //Should move to another page in a later time***********************************************!!!!
        #region Modify
        public void ShowModifyStatus()
        {
            if (this.Application != null)
            {
                OCRCtrl.ShowModifyStatus();
            }
        }

        public void EndModifyStatus()
        {
            if (this.Application != null)
            {
                OCRCtrl.EndModifyStatus();
            }
        }

        public void Modify()
        {
            IOCR OCRService = AppContainer.Instance[ServiceConst.OCRService] as IOCR;
            BEGDC.CC.Entity.Application App = OCRService.GetApplication(this.AppID);
            if (App != null)
            {
                IList customerAttendee = new ArrayList();
                IList alAttendee = new ArrayList();
                OCRCtrl.BuildModificationChange(ref App, ref customerAttendee, ref alAttendee);
                OCRService.SaveEZModification(App, customerAttendee, alAttendee);
            }
        }
        #endregion
    }
}
